<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Enums\AvailableStatus;
use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\FrontendUser;
use App\Models\PurchaseWhiteList;
use Illuminate\Support\Arr;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class EarlyBuyController extends Controller
{
    /** 查询提前购用户配置清单 */
    public function getEarlyBuyWhiteList($productId)
    {
        $query = PurchaseWhiteList::query()
            ->where('product_id', $productId)
            ->where('status', AvailableStatus::ENABLED)
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';

                return $q->where('user_mobile', 'like', $likeVal);
            });

        return paginate_result($query);
    }

    /** 保存提前购配置 */
    public function save($productId)
    {
        request()->validate([
            'early_buy_minutes' => 'required | integer',
        ]);

        //删除已启用的配置
        PurchaseWhiteList::query()
            ->where('product_id', $productId)
            ->where('status', AvailableStatus::ENABLED)
            ->delete();

        //启用新上传配置
        PurchaseWhiteList::query()
            ->where('product_id', $productId)
            ->where('status', AvailableStatus::DISABLED)
            ->update([
                'status' => AvailableStatus::ENABLED,
                'early_buy_minutes' => request()->early_buy_minutes,
            ]);
    }

    /** 上传用户清单文件 */
    public function uploadFile($productId)
    {
        request()->validate([
            'file' => 'required | file',
        ]);

        /** @var AgentUser $user */
        $user = auth()->user();

        $file = request()->file('file');
        $fileHandler = fopen($file, 'r');
        $ext = $file->getClientOriginalExtension();
        if (!in_array($ext, ['csv'])) {
            throw new AdminException('仅支持CSV格式的文件');
        }
        $data = [];
        fgetcsv($fileHandler, 1000, ',');
        $line = 1;
        while (($row = fgetcsv($fileHandler, 1000, ',')) !== false) {
            ++$line;
            $mobile = Arr::get($row, 0);
            $buyLimit = Arr::get($row, 1);
            if (!is_numeric($buyLimit)) {
                throw new AdminException('无效的购买数量[第' . $line . '行]');
            }
            $data[] = [
                'mobile' => $mobile,
                'buy_limit' => $buyLimit,
            ];
        }
        $mobiles = array_unique(Arr::pluck($data, 'mobile'));
        if (count($mobiles) < count($data)) {
            throw new AdminException('存在重复的手机号');
        }
        $users = FrontendUser::query()
            ->where('agent_id', $user->agent_id)
            ->whereIn('mobile', $mobiles)
            ->get()
            ->mapWithKeys(function (FrontendUser $user) {
                return [$user->mobile => $user];
            });

        $batchValues = [];
        foreach ($data as $row) {
            $mobile = $row['mobile'];
            if (!Arr::has($users, $mobile)) {
                throw new AdminException("手机号【{$mobile}】未找到");
            }

            $batchValues[] = [
                'product_id' => $productId,
                'user_mobile' => $mobile,
                'buy_limit' => $row['buy_limit'],
                'status' => AvailableStatus::DISABLED,
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        //删除所有未启用的配置
        PurchaseWhiteList::query()
            ->where('product_id', $productId)
            ->where('status', AvailableStatus::DISABLED)
            ->delete();

        PurchaseWhiteList::insert($batchValues);
    }
}
